<template>
  <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      :http-request="customUpload"
      :on-error="handleError"
      :before-upload="beforeUpload"
      accept=".jpg,.png"
      :show-file-list="false"
  >
    <el-icon class="el-icon--upload">
      <img src="../../assets/upload.svg" alt="上传" style="height: 60%">
    </el-icon>
    <div class="el-upload__text">
      拖入文件 /<em>点击上传</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 500kb
      </div>
    </template>
  </el-upload>
</template>

<script setup>

import { ref,defineEmits } from 'vue'
import axios from 'axios'


const emit = defineEmits(["Uploaded"])

// 自定义上传函数
const customUpload = async (options) => {
  const { onProgress, onSuccess, onError, file, headers } = options

  // 构造 FormData
  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await axios.post('http://localhost:8000/upload/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        const percent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
        )
        onProgress({ percent })
      },
    })

    handleSuccess(response.data,file)
  } catch (error) {
    onError({ err: error })
  }


}

// 文件上传前处理
const beforeUpload = (file) => {
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type)
  if (!isValidType) {
    alert('只能上传 JPG/PNG 格式的图片！')
    return false
  }

  const isValidSize = file.size / 1024 / 1024 < 5 // 小于 5MB
  if (!isValidSize) {
    alert('图片大小不能超过 5MB！')
    return false
  }

  return true
}

// 成功回调
const handleSuccess = (response,file) => {
  console.log('上传成功:', response.filename)
  emit("Uploaded",response.filename)
  alert('文件上传成功！')
}

// 失败回调
const handleError = (error, file) => {
  console.error('上传失败:', error, file)
  alert('文件上传失败，请重试。')
}


</script>